<script setup>
import { userUpdatePasswordService } from '@/api/userinfo'
import { useUserStore } from '@/stores'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
// 表单数据
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: '',
})

// 表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateOldPwd, trigger: 'blur' },
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateNewPwd, trigger: 'blur' },
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: validateRePwd, trigger: 'blur' },
  ],
}

// 自定义校验：原密码和新密码不能一样
function validateOldPwd(rule, value, callback) {
  if (value === pwdForm.value.new_pwd) {
    callback(new Error('原密码和新密码不能一样'))
  }
  else {
    callback()
  }
}

// 自定义校验：新密码和确认密码必须一样
function validateNewPwd(rule, value, callback) {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码和原密码不能一样'))
  }
  else {
    callback()
  }
}

function validateRePwd(rule, value, callback) {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('新密码和确认密码必须一样'))
  }
  else {
    callback()
  }
}

const router = useRouter()
const userStore = useUserStore()
// 提交表单
// 提交表单
function onSubmit(formEl) {
  if (!formEl)
    return
  formEl.validate(async (valid) => {
    if (valid) {
      await userUpdatePasswordService(pwdForm.value)
      // eslint-disable-next-line no-undef
      ElMessage.success('密码修改成功')
      // 密码修改成功后，退出重新登陆
      // 清除本地存储的token
      userStore.setToken('')
      userStore.setUser({})
      // 跳转到登录页
      router.push('/login')
    }
    else {
      // eslint-disable-next-line no-undef
      ElMessage.error('请检查表单输入')
    }
  })
}

// 重置表单
function onReset(formEl) {
  if (!formEl)
    return
  formEl.resetFields()
}
</script>

<template>
  <PageContainer title="修改密码">
    <el-form ref="formRef" :model="pwdForm" :rules="rules" label-width="100px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit($refs.formRef)">
          修改密码
        </el-button>
        <el-button @click="onReset($refs.formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
